<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>深拷贝</title>
</head>
<body>

</body>
</html>

<script>
  let obj = {
    name: '张三',
    age: 18,
    like: [1,[1,2]]
  }

  // 浅拷贝直接复制 不用递归复制

  // 寻找数组中满足条件的的对象
  function find (list, f) {
    return list.filter(f)[0]
  }

  /*
  * 考虑到深拷贝的递归赋值
  * 防止陷入死循环，利用缓存进行处理操作
  * */
  function deepCopy (obj, cache = []) {
    if (!obj || typeof obj !== 'object') {
      return obj
    }

    // 判断是否拷贝完成
    const over = find(cache, q => q.curObj === obj)
    if (over) {
      return over.copy
    }

    let copy = Array.isArray(obj) ? [] : {}

    cache.push({
      curObj: obj,
      copy
    })

    Object.keys(obj).forEach(w => {
      copy[w] = deepCopy(obj[w], cache)
    })
    return copy
  }
  let o = deepCopy(obj)
  o.like[1][0] = 66
  console.log('deepCopy:', o)
  console.log('obj:', obj)

  // 一层结构深拷贝
  Object.assign()
  // JSON
  JSON.stringify()
  JSON.parse()
</script>